package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * RabbitMQ新增/更新索引库
     * @param jsonString
     */
    @Override
    public void saveOrUpdateEs(String jsonString) {
        Item item = JSON.parseObject(jsonString, Item.class);
        ItemDoc itemDoc = new ItemDoc(item);
        IndexRequest request = new IndexRequest("item");
        // 上面如果不给索引库会报异常，长这样的，异常很清楚ActionRequestValidationException: Validation Failed: 1: index is missing;
        request.id(item.getId().toString());
        String jsonStr = JSON.toJSONString(itemDoc);
        request.source(jsonStr, XContentType.JSON);
        try {
            IndexResponse indexResponse = client.index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * RabbitMQ根据id删除索引库文档
     * @param id
     */
    @Override
    public void deleteEs(String id) {
        DeleteRequest request = new DeleteRequest("item",id);
        try {
            DeleteResponse response = client.delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 条件查询索引库信息
     * @param requestParams
     * @return
     */
    @Override
    public PageDTO<ItemDoc> search(RequestParams requestParams) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL request.source()
            // {"key":"","page":1,"size":20,"sortBy":"default"}

            // 条件查询
            buildBasicQuery(requestParams,request);

            // 返回结果处理
            // 分页查询
            request.source()
                    .from((requestParams.getPage() - 1) * requestParams.getSize())
                    .size(requestParams.getSize());


            // 3.发送请求，得到响应结果
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            // 4.解析响应结果【另见本类方法handleResponse()】
            return handleResponse(response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 结果解析
     * @param response
     * @return
     */
    private PageDTO handleResponse(SearchResponse response) {
        // 4解析结果【对比着kibana响应结果进行写】
        SearchHits searchHits = response.getHits();
        // 4.1查询的总条数
        long total = searchHits.getTotalHits().value;
        log.info("[查询结果解析===>查询总条数为：{}]", total);
        // 4.2查询的结果数组
        // 4.3遍历
        SearchHit[] hits = searchHits.getHits();
        // 创建ItemDoc的List集合，进行封装HotelDoc对象
        List<ItemDoc> itemDocList = new ArrayList<>();
        for (SearchHit hit : hits) {
            // 4.3.1得到文档source
            String json = hit.getSourceAsString();
            // 4.3.2反序列化
            ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);
            // 将HotelDoc对象封装进List集合
            itemDocList.add(itemDoc);
            // 获取高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            // log.info("[查询结果解析===>高亮结果Map：{}]", highlightFields);
            if (!CollectionUtils.isEmpty(highlightFields)) {
                // 根据字段名获取高亮结果
                HighlightField highlightField = highlightFields.get("name");
                if ((highlightField != null)) {
                    // 获取高亮值
                    String name = highlightField.getFragments()[0].string();
                    log.info("[查询结果解析===>高亮结果name：{}]", name);
                    // 覆盖非高亮的结果
                    itemDoc.setName(name);
                }
            }
        }
        return new PageDTO(total,itemDocList);
    }

    /**
     * 查询条件
     * @param requestParams
     * @param request
     */
    private void buildBasicQuery(RequestParams requestParams, SearchRequest request) {
        // 2.1准备BooleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 全文检索：关键字查询    算分，must
        if (StringUtils.isNotBlank(requestParams.getKey())) {
            boolQuery.must(QueryBuilders.matchQuery("all", requestParams.getKey()));
        } else {
            // 特别注意啦，就是这里出的问题，开始这里用的filter，
            // 结果在算分那里，广告小图标可以显示但是没有办法置顶！！！
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        // 构建高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name");
        highlightBuilder.preTags("<em style='color:red'>");
        highlightBuilder.postTags("</em>");
        // ※※※特别注意了：此处要判断高亮字段与查询内容是否一致，不一致需要requireFieldMatch(false)，否则前面做的都白费，高亮结果为空
        highlightBuilder.requireFieldMatch(false);
        request.source().highlighter(highlightBuilder);


        // 精确查询：词条term，范围range   不算分，filter
        if (StringUtils.isNotBlank(requestParams.getCategory())) {
            // 分类 category
            log.info("[分类查询===>类别为：{}]", requestParams.getCategory());
            boolQuery.filter(QueryBuilders.termQuery("category", requestParams.getCategory()));
        }
        if (StringUtils.isNotBlank(requestParams.getBrand())) {
            // 品牌 brand
            log.info("[品牌查询===>品牌为：{}]", requestParams.getBrand());
            boolQuery.filter(QueryBuilders.termQuery("brand", requestParams.getBrand()));
        }
        if (requestParams.getMinPrice() != null && requestParams.getMaxPrice() != null) {
            // 价格区间 price
            log.info("[价格区间查询，最低价格：{}，最高价格：{}]", requestParams.getMinPrice(), requestParams.getMaxPrice());
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .gte(requestParams.getMinPrice())
                    .lte(requestParams.getMaxPrice()));
        }

        // 将bool条件放入 request.source()
        // request.source().query(boolQuery);
        // 算分置顶
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询
                        boolQuery,
                        // function score数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中一个function score元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD",true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)

                                )
                        });
        // 将算分条件放入 request.source()
        request.source().query(functionScoreQuery);
    }

    /**
     * 过滤项聚合
     * @param requestParams
     * @return
     */
    @Override
    public Map<String, List<String>> getFilters(RequestParams requestParams) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            buildBasicQuery(requestParams,request);
            // 2.1query
            // 2.2设置size
            request.source().size(0);
            // 2.3聚合
            buildAggregation(request);
            // 3.发出请求
            SearchResponse response = client.search(request,RequestOptions.DEFAULT);
            // 4.解析结果
            Map<String,List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            // 4.1分类
            List<String> categoryList = getAggByName(aggregations,"categoryAgg");
            result.put("category",categoryList);
            // 4.1品牌
            List<String> brandList = getAggByName(aggregations,"brandAgg");
            result.put("brand",brandList);
            // 5.返回结果
            return result;
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }

    /**
     * 聚合
     * @param request
     */
    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(100));
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100));
    }

    /**
     * 根据聚合名称获取结果集
     * @param aggregations
     * @param aggName
     * @return
     */
    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 4.1根据聚合名称获取聚合结果
        Terms termsName = aggregations.get(aggName);
        // 4.2获取buckets
        List<? extends Terms.Bucket> buckets = termsName.getBuckets();
        // 4.3遍历
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 4.4获取key
            String keyAsString = bucket.getKeyAsString();
            brandList.add(keyAsString);
        }
        return brandList;
    }
}
